/*
 * This file is Copyright 2002-2006 Loyola University Chicago,
 * Department of Computer Science and the Emerging Technologies Laboratory.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License via
 *    http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.citep.web.gwt.validators;

import java.util.ArrayList;

import com.google.gwt.user.client.ui.Widget;

/*
 * Groups together a series of widgets and their validators. Its main purpose is to allow
 * one to validate them all at the same time by calling validate() just once. Also note that
 * if a DataElement with a given id fails to validate, all subsequent DataElements with the
 * same id will not be tested.
 */
public class ValidatorGroup {
	
	private ArrayList dataElements;
	
	public ValidatorGroup() {
		dataElements = new ArrayList();
	}
	
	public void addValidator(String name, Widget w, Validator v) {
		addValidator(new DataElement(name, w),v);

	}
	
	public void addValidator(DataElement dataElement, Validator v) {
		v.setDataElement(dataElement);
		dataElements.add(v);
	}
	
	public boolean validate() {
		if(dataElements == null)
			return true;

		ArrayList invalidElements = new ArrayList();
		
		for(int i = 0; i < dataElements.size(); i++) {
			Validator v = (Validator)dataElements.get(i);
			
			//this dataElement already has an error, so don't validate any subsequent ones
			if(invalidElements.contains(v.getDataElement().getName()))
				continue;
			
			//if it's invalid add it to the list of invalid dataelements
			if(!v.validate()) {
				invalidElements.add(v.getDataElement().getName());
			}
		}
		
		return invalidElements.size() < 1;
	}
}
